package com.example.demo.service.impl;

import com.example.demo.admin.dto.AddUser;
import com.example.demo.admin.dto.RegisterDto;
import com.example.demo.admin.dto.SearchDto;
import com.example.demo.admin.dto.UserDto;
import com.example.demo.admin.pojo.PageResult;
import com.example.demo.admin.pojo.User;
import com.example.demo.admin.vo.*;
import com.example.demo.exception.LoginException;
import com.example.demo.mapper.DeptMapper;
import com.example.demo.mapper.JobMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.properties.JwtProperties;
import com.example.demo.service.UserService;
import com.example.demo.utils.BaseContext;
import com.example.demo.utils.JwtUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private JobMapper jobMapper;

    @Override
    public void addUser(RegisterDto registerDto) {
        User user = new User();
        user.setCreateTime(LocalDateTime.now());
        user.setUsername(registerDto.getUsername());
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword(registerDto.getPassword());
        user.setEntrydate(LocalDate.now());
        userMapper.addUser(user);
    }

    @Override
    public LoginVo login(RegisterDto registerDto) {
        User user = userMapper.login(registerDto);
        if (user == null) {
            throw new LoginException("用户名或者密码错误");
        }
        //生成令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        return LoginVo.builder()
                .token(token)
                .build();
    }

    /**
     * 查看用户是否存在
     *
     * @param
     */
    @Override
    public void exitUser(String username) {
        User user = userMapper.exitUser(username);
        System.out.println(user);
        if (user != null) {
            throw new LoginException("用户名已存在");
        }
    }

    /**
     * 用户详细信息
     */
    @Override
    public UserVo getUserDetail() {
        Long currentId = BaseContext.getCurrentId();
        log.info("用户id{}", currentId);
        return userMapper.getUserById(currentId);
    }

    /**
     * 修改用户信息
     *
     * @param userDto
     */
    @Override
    public void updateUser(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateUser(user);
    }

    /**
     * 获取部门全部信息
     */
    @Override
    public List<DepartmentVO> getDepartments() {
        List<DepartmentVO> list = deptMapper.getDepartments();
        return list;
    }

    /**
     * 职业全部分类
     *
     * @return
     */
    @Override
    public List<DepartmentVO> getJobs() {
        List<DepartmentVO> list = jobMapper.getJobs();
        return list;
    }

    /**
     * 分页查询数据
     */
    @Override
    public PageResult getAllUser(SearchDto searchDto) {
        Long id = BaseContext.getCurrentId();
        searchDto.setId(id);
        PageHelper.startPage(searchDto.getCurrentPage(), searchDto.getPageSize());
        Page<PageResultVo> page = userMapper.getAllUser(searchDto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 添加用户
     */
    @Override
    public void saveUser(AddUser addUser) {
        User user = new User();
        BeanUtils.copyProperties(addUser, user);
        user.setCreateTime(LocalDateTime.now());
        user.setEntrydate(LocalDate.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword("123456");
        userMapper.addUser(user);
    }

    /**
     * 删除用户
     */
    @Override
    public void deleteUser(String username) {
        userMapper.deleteUser(username);
    }

    /**
     * 重置密码
     */
    @Override
    public void resetPassword(String username) {
        User user = User.builder()
                .password("123456")
                .username(username)
                .updateTime(LocalDateTime.now())
                .build();
        userMapper.updateUser(user);
    }

    /**
     * 用户数据
     */
    @Override
    public StatisticsVo UserStatistics() {
        //获取年份
        int year = Year.now().getValue();
        //存储每月的数据
        ArrayList<String> xDataList = new ArrayList<>();
        ArrayList<Integer> yDataList = new ArrayList<>();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int month = 1; month < 13; month++) {
            String xData = String.valueOf(year) + '-' + String.valueOf(month);
            xDataList.add(xData);
            //创建YearMonth对象
            YearMonth yearMonth = YearMonth.of(year, month);
            //获取最后一天
            LocalDate endOfMonth = yearMonth.atEndOfMonth();
            String lastTime = pattern.format(endOfMonth);
            Integer sum = userMapper.selectEveryMonths(lastTime);
            yDataList.add(sum);
        }
        String listDateTime = xDataList.stream().collect(Collectors.joining(","));
        String listDate = yDataList.stream().map(String::valueOf).collect(Collectors.joining(","));
        return StatisticsVo.builder()
                .listDateTime(listDateTime)
                .listData(listDate)
                .build();
    }

    @Override
    public void updateAvatar(String image,String username) {
        User user = User.builder()
                .updateTime(LocalDateTime.now())
                .image(image)
                .username(username)
                .build();
        userMapper.updateUser(user);
    }
}
